#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("简单记事本");
    //获取菜单栏
    QMenuBar* menuBar=this->menuBar();
    //添加菜单
    QMenu* menu=new QMenu("文件");
    menuBar->addMenu(menu);
    //添加菜单项
    QAction* action1=new QAction("打开");
    QAction* action2=new QAction("保存");
    menu->addAction(action1);
    menu->addAction(action2);
    //指定输入框
    edit=new QPlainTextEdit();
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);//设置字体
    this->setCentralWidget(edit);

    //连接action信号槽
    connect(action1,&QAction::triggered,this,[this](){
        //先弹出对话框,让用户选择打开哪个文件
        QString path=QFileDialog::getOpenFileName(this);
        //将文件路径显示到状态栏
        statusBar()->showMessage(path);
        //根据路径构建一个QFile对象
        QFile file(path);
        if(file.open(QIODevice::ReadOnly)==false)
        {
            statusBar()->showMessage(path+"打开失败");
            return;
        }
        //需要确保打开文件是文本文件
        QString date=file.readAll();
        //关闭文件
        file.close();
        //将读取到的内容设置到文本中
        this->edit->setPlainText(date);
    });

    connect(action2,&QAction::triggered,this,[this](){
        //先弹出保存文件对话框
        QString path=QFileDialog::getSaveFileName(this);
        //将文件路径显示到状态栏
        statusBar()->showMessage(path);
        //根据路径构建一个QFile对象
        QFile file(path);
        if(file.open(QIODevice::WriteOnly)==false)
        {
            statusBar()->showMessage(path+"打开失败");
            return;
        }
        //写文件
        const QString& text=this->edit->toPlainText();
        file.write(text.toUtf8());
        //关闭文件
        file.close();

    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

